#include <boost/uuid/uuid_generators.hpp>
#include <boost/uuid/uuid_io.hpp>

#include "common/log/log.h"

#include "session.h"

namespace
{
std::chrono::time_point<std::chrono::system_clock> now()
{
    return std::chrono::system_clock::now();
}
} // namespace

Session::Session(Elements::UserPtr user)
    : m_uuid(boost::uuids::random_generator()())
    , m_lastActionTime(now())
    , m_user(user)
{
    assert(m_user);
    m_user->setIsOnline(true);
}

Session::~Session()
{
    assert(m_user);
    m_user->setIsOnline(false);
}

Uuids::Uuid Session::uuid() const
{
    return m_uuid;
}

bool Session::checkDuration() const
{
    if (0 == m_availableDuration)
        return true;

    const auto currentDuration = now() - m_lastActionTime;
    const unsigned seconds = std::chrono::duration_cast<std::chrono::seconds>(currentDuration).count();
    bool result(seconds <= m_availableDuration);
    if (!result)
    {
        assert(m_user);
        LOG_INFO
            << "Срок действия сеанса пользователя истек."
            << " session.uuid=" << boost::uuids::to_string(m_uuid)
            << " user.login=" << m_user->login();
        m_user->setIsOnline(false);
    }
    return result;
}

Elements::UserPtr Session::user() const
{
    return m_user;
}

void Session::keepAlive()
{
    m_lastActionTime = now();
}
